package com.gouda.core.dao;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.gouda.core.entity.AddressEntity;
import com.gouda.core.enums.EnumDefault;
import com.gouda.core.enums.GeneralStateEnum;
import lombok.extern.slf4j.Slf4j;
import org.amethyst.atlas.db.MagicDao;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Created by KGL on 2015/12/7.
 */
@Slf4j
@Repository
public class AddressDao extends MagicDao {
    private static final String BASE_SQL = " select id,uid,name,phone,address,isdefault from address ";

    /**
     * 查询客户地址列表
     * @param uid
     * @param start
     * @param end
     * @param start
     * @param end
     * @return
     */
    public List<AddressEntity> lookupCustomerAddresses(final long uid, final int start, final int end) {
        if(uid<=0L) {
            return Lists.newArrayList();
        }

        final String whereSql = " where uid=:uid and stat=:stat ";
        final String orderSql = " order by isdefault desc ";
        final String limitSql = " limit :start,:end";

        String querySql = BASE_SQL + whereSql + orderSql;

        final Map<String,Object> params = Maps.newHashMap();
        params.put("uid", uid);
        params.put("stat", GeneralStateEnum.YES.getCode());

        if(start>=0 && end>0) {
            querySql += limitSql;
            params.put("start", start);
            params.put("end", end);
        }

        return super.list(AddressEntity.class, querySql, params);
    }

    /**
     * 查询客户默认地址
     * @param uid
     * @return
     */
    public AddressEntity lookupUserDefaultAddress(final long uid) {
        if(uid<=0L) {
            return null;
        }

        final String whereSql = " where uid=:uid and stat=:stat and isdefault=:isdefault ";

        String querySql = BASE_SQL + whereSql;

        final Map<String,Object> params = Maps.newHashMap();
        params.put("uid", uid);
        params.put("stat", GeneralStateEnum.YES.getCode());
        params.put("isdefault", EnumDefault.IS.getCode());

        return super.unique(AddressEntity.class, querySql, params);
    }

}
